#! /bin/bash
ISO_MOUNTPATH="/mnt/graveur"
ISO_REMOTEPATH=""
USER_LIST="/home/sauvegarde/sauv_users.txt"
if [ -r ${USER_LIST} ]
then
        USERS=`cat ${USER_LIST}`
else
        echo "Impossible de lire ${USER_LIST}"
        exit 1
fi
USERS=`cat ${USER_LIST}`
DIRS=""
DIR_LIST=""
for USERNAME in $USERS
do
        ln -s -f "/home/$USERNAME" /home/links/
        REMOTE_COMPUTER=`grep /mnt/$USERNAME /etc/fstab | awk -F ' ' '{print $1}' | awk -F '/' '{print $3}'`
        IS_ACTIVE=`nmblookup ${REMOTE_COMPUTER} | grep failed | wc -l`
        if [ ${IS_ACTIVE} -lt 1 ]
        then
                mount /mnt/$USERNAME
        else
                echo "Impossible de se connecter à ${REMOTE_COMPUTER}"
                continue
        fi
        DIR_LIST="/home/sauvegarde/${USERNAME}.dir"
        if [ -r ${DIR_LIST} ]
        then
                DIRS=`cat ${DIR_LIST}`
        else
                echo "Impossible de lire ${DIR_LIST}"
                continue
        fi
        for DIR in $DIRS
        do
                if [ -d /mnt/$USERNAME/$DIR ]
                then
                        if [ -d /home/$USERNAME/$DIR ]
                        then
                                sleep 0
                        else
                                mkdir -p /home/$USERNAME/$DIR
                        fi
                        cd /home/$USERNAME/$DIR
                        #cp -r "/mnt/$USERNAME/$DIR/"* .
                        rsync -av "/mnt/$USERNAME/$DIR/"* .
                else
                        echo "Impossible de copier /mnt/$USERNAME/$DIR"
                        continue
                fi
        done
        sync
        umount /mnt/$USERNAME
        sleep 5
done
LABEL=`date +"%Y_%m_%d"`
ISO_FILENAME="/home/sauvegarde/${LABEL}.iso"
mkisofs -f -R -r -J -V "$LABEL" -o "${ISO_FILENAME}" /home/links
REMOTE_COMPUTER=`grep ${ISO_MOUNTPATH} /etc/fstab | awk -F ' ' '{print $1}' | awk -F '/' '{print $3}'`
IS_ACTIVE=`nmblookup ${REMOTE_COMPUTER} | grep failed | wc -l`
if [ ${IS_ACTIVE} -lt 1 ]
then
        mount ${ISO_MOUNTPATH}
else
        echo "Impossible de se connecter à ${REMOTE_COMPUTER}"
        exit 1
fi
cp "${ISO_FILENAME}" "${ISO_MOUNTPATH}/${ISO_REMOTEPATH}"
sync
touch "${ISO_MOUNTPATH}/${ISO_REMOTEPATH}/gravure_ok.txt"
sync
umount ${ISO_MOUNTPATH}
#rm -f "${ISO_FILENAME}"
rm /home/links/*